package ru.spb.osll.myfit.util;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class CollectionUtils {
	public static <T, U> Map<T, U> map(List<T> keys, List<U> values) {
		HashMap<T, U> res = new HashMap<T, U>();
		if (keys.size() != values.size()) {
			throw new IllegalArgumentException(
					"keys and values size should be equal");
		}

		Iterator<U> valuesIt = values.iterator();

		for (T key : keys) {
			res.put(key, valuesIt.next());
		}

		return res;
	}

	public static <T> List<T> list(T... args) {
		LinkedList<T> res = new LinkedList<T>();
		for (T arg : args) {
			res.add(arg);
		}
		return res;
	}

	public static <T> List<T> filter(Collection<T> list, Filter<T> filter) {
		LinkedList<T> result = new LinkedList<T>();
		for(T elem : list) {
			if(filter.passes(elem)) {
				result.add(elem);
			}
		}
		return result;
	}

	public static <T> List<T> filterOdd(Collection<T> list) {
		return filterOddOrEven(list, true);
	}

	public static <T> List<T> filterEven(Collection<T> list) {
		return filterOddOrEven(list, false);
	}

	public static <T, U> Pair<T, U> makePair(T first, U second) {
		return new Pair<T, U>(first, second);
	}

	private static <T> List<T> filterOddOrEven(Collection<T> list,
			boolean oddRecords) {
		LinkedList<T> result = new LinkedList<T>();
		boolean isOddRecord = false;
		for (T elem : list) {
			if ((isOddRecord && oddRecords) || (!isOddRecord && !oddRecords)) {
				result.add(elem);
			}
			isOddRecord = !isOddRecord;
		}
		return result;
	}
}
